#include "tcpserver.h"

TcpServer::TcpServer(QObject *parent): QTcpServer(parent)
{
    connect(this, &QTcpServer::newConnection, this, &TcpServer::onNewConnection);
}

void TcpServer::startServer(int port)
{
    if (listen(QHostAddress::Any, port)) {
        qDebug() << "Server started";
    } else {
        qDebug() << "Server failed to start";
    }
}

void TcpServer::sendData(QString data)
{
    if(clientSocket && clientSocket->isValid())
        clientSocket->write(data.toUtf8());
}

void TcpServer::sendData(char *data, quint64 len)
{
    static int count = 0;

    if(clientSocket != NULL)
    {
        if(clientSocket->isValid())
        {
            count++;
            if(count >= 10)
            {
                clientSocket->write("1");
                clientSocket->write(data, len);
            }
        }
    }
}

void TcpServer::onNewConnection()
{
    qDebug() << "onNewConnection";
    clientSocket = nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, [&]()
    {
        QByteArray data = clientSocket->readAll();
        emit sigRecv(data);
    });
    connect(clientSocket, &QTcpSocket::disconnected, clientSocket, &QTcpSocket::deleteLater);
}
